package cn.iocoder.yudao.module.testequipment.service.testequipment;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.testequipmentuse.dal.dataobject.testequipmentuse.TestEquipmentUseDO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.testequipment.controller.admin.testequipment.vo.*;
import cn.iocoder.yudao.module.testequipment.dal.dataobject.testequipment.TestEquipmentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.testequipment.dal.mysql.testequipment.TestEquipmentMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.testequipment.enums.ErrorCodeConstants.*;
import cn.iocoder.yudao.module.testequipmentuse.dal.mysql.testequipmentuse.TestEquipmentUseMapper;
/**
 * 参试设备管理表 Service 实现类
 *
 * @author wwwhk
 */
@Service
@Validated
public class TestEquipmentServiceImpl implements TestEquipmentService {

    @Resource
    private TestEquipmentMapper testEquipmentMapper;
    @Resource
    private TestEquipmentUseMapper equipmentUseMapper;



    @Override
    public Long createTestEquipment(TestEquipmentSaveReqVO createReqVO) {
        // 插入
        TestEquipmentDO testEquipment = BeanUtils.toBean(createReqVO, TestEquipmentDO.class);
        testEquipmentMapper.insert(testEquipment);

        // 返回
        return testEquipment.getId();
    }

    @Override
    public void updateTestEquipment(TestEquipmentSaveReqVO updateReqVO) {
        // 校验存在
        validateTestEquipmentExists(updateReqVO.getId());
        // 更新
        TestEquipmentDO updateObj = BeanUtils.toBean(updateReqVO, TestEquipmentDO.class);
        testEquipmentMapper.updateById(updateObj);
    }

    @Override
    public void deleteTestEquipment(Long id) {
        // 校验存在
        validateTestEquipmentExists(id);
        // 删除
        testEquipmentMapper.deleteById(id);
    }

    @Override
        public void deleteTestEquipmentListByIds(List<Long> ids) {
        // 删除
        testEquipmentMapper.deleteByIds(ids);
        }


    private void validateTestEquipmentExists(Long id) {
        if (testEquipmentMapper.selectById(id) == null) {
            throw exception(TEST_EQUIPMENT_NOT_EXISTS);
        }
    }

    @Override
    public TestEquipmentDO getTestEquipment(Long id) {
        return testEquipmentMapper.selectById(id);
    }

    @Override
    public PageResult<TestEquipmentDO> getTestEquipmentPage(TestEquipmentPageReqVO pageReqVO) {
        return testEquipmentMapper.selectPage(pageReqVO);
    }
    
    @Override
    public PageResult<TestEquipmentMyUseRespVO> getMyEquipmentUsePage(TestEquipmentPageReqVO pageReqVO) {
        // 由于需要关联查询test_equipment_use表获取使用状态为"已出库"的记录，
        // 这里需要使用自定义SQL查询
        
        // 创建分页对象
        IPage<TestEquipmentMyUseRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        
        // 调用Mapper方法查询已出库的设备记录
        IPage<TestEquipmentMyUseRespVO> resultPage = testEquipmentMapper.selectMyEquipmentUsePage(page, pageReqVO);
        
        // 转换为前端需要的分页结果
        return new PageResult<>(resultPage.getRecords(), resultPage.getTotal());
    }
    /**
     * 实现设备状态更新：入库时设置为未出库（0）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTestEquipmentStatus(Long id, Integer useStatus) {
        // 1. 校验设备是否存在
        TestEquipmentDO equipment = testEquipmentMapper.selectById(id);
        if (equipment == null) {
            throw new ServiceException(TEST_EQUIPMENT_NOT_EXISTS);
        }

        // 2. 更新设备表的使用状态
        TestEquipmentDO updateDO = new TestEquipmentDO();
        updateDO.setId(id);
        updateDO.setUseStatus(useStatus); // 0=未出库，1=已出库
        testEquipmentMapper.updateById(updateDO);

        // 3. 可选：同步更新设备使用记录表的操作类型（若业务需要）
        // 例如：入库时添加一条"入库"类型的记录（operation_type=2，需与字典一致）
        if (useStatus == 0) {
            TestEquipmentUseDO useDO = new TestEquipmentUseDO();
            useDO.setEqId(id);
            useDO.setOperationType(2); // 2=入库（与出库1对应）
            useDO.setUpdater(SecurityFrameworkUtils.getLoginUserNickname());
            useDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
            useDO.setUpdateTime(LocalDateTime.now());
            equipmentUseMapper.insert(useDO);

        }



    }


}